package com.lingjtx.common.thread.core;

import jakarta.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class ThreadPoolShutdown {

    private static final Logger log = LoggerFactory.getLogger(ThreadPoolShutdown.class);

    private final ThreadPoolManager threadPoolManager;

    public ThreadPoolShutdown(ThreadPoolManager threadPoolManager) {
        this.threadPoolManager = threadPoolManager;
    }

    @PreDestroy
    public void onShutdown() {
        log.info("Spring 应用关闭中，开始优雅关闭线程池...");

        Map<String, ExecutorService> pools = threadPoolManager.getAllPools();
        pools.forEach((name, executor) -> {
            try {
                log.info("正在关闭线程池 [{}]...", name);
                executor.shutdown(); // 如果需要强制立即关闭可改为 shutdownNow()
                if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {
                    executor.shutdownNow(); // 强制关闭
                }
            } catch (Exception e) {
                log.error("关闭线程池 [{}] 时发生异常：{}", name, e.getMessage(), e);
            }
        });
        log.info("线程池关闭完毕。资源清理完成。");
    }
}
